#include "importdialog.h"
#include "ui_importdialog.h"
#include "msginf.h"
#include <QFileDialog>
#include <QDebug>
#include <QTimer>
#include <QFile>

ImportDialog::ImportDialog(CSql* sql,QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ImportDialog),
    m_Sql(sql)
{
    ui->setupUi(this);
    this->setFixedSize(340,138);
    this->setWindowTitle(_("ImportData"));
    ui->labelFile->setText(_("File Name:"));
    ui->labelProgress->setText(_("Progress:"));
    ui->pBOK->setText(_("Import"));
    ui->pBCancel->setText(_("Cancel"));
    ui->progressBar->setValue(0);
    ui->pBOpen->setText(_("Select File"));
    ui->checkBox->setText(_("New Import"));


    connect(ui->pBOpen,&QPushButton::clicked,this,OnOpen);
    connect(ui->pBCancel,&QPushButton::clicked,[=](){
       this->reject();
    });
    connect(ui->pBOK,SIGNAL(clicked(bool)),this,SLOT(OnOK()));
}

ImportDialog::~ImportDialog()
{
    delete ui;
}

void ImportDialog::OnOK()
{
    qDebug() << __FUNCTION__;
    ui->progressBar->setValue(0);
    ui->pBOK->setEnabled(false);

    QTimer::singleShot(1000,this,SLOT(DoProcess()));
}
void ImportDialog::OnOpen()
{
    qDebug() << __FUNCTION__;
    QString fileName = QFileDialog::getOpenFileName(this, _("Select File"),
                                                    "./",
                                                    _("CSV (*.CSV *.csv)"));
    ui->lineEdit->setText(fileName);

}

void ImportDialog::DoProcess()
{
    qDebug() << __FUNCTION__;

    if(ui->lineEdit->text()==""){
        MSGINF::MsgShowOk(this,_("Info"),_("Select File Is Empty,Please Select File."));
    }
    else{//工程 测量点 图层 gap gap- gap+ flush flush- flush+
        QFile file(ui->lineEdit->text());
        if (file.open(QFile::ReadOnly)) {
            ui->labelProgress->setText(_("Parsing:"));
            ui->progressBar->setRange(0,100);
            ui->progressBar->setValue(30);
            m_ImportData.clear();
            char buf[1024];
            std::string sdata;
            qint64 lineLength = file.readLine(buf, sizeof(buf));
            while (lineLength != -1) {
                // the line is available in buf
                sdata.append(buf,lineLength);
                sdata = MSGINF::replace_str(sdata,"\r\n","");
                m_ImportData.push_back(sdata);

                qDebug() << sdata.c_str() ;
                sdata.clear();
                sdata ="";
                memset(buf,0x00,sizeof(buf));
                lineLength = file.readLine(buf, sizeof(buf));
            }
            DoImport();
        }
    }

    ui->pBOK->setEnabled(true);
}

void ImportDialog::DoImport()
{
    ui->labelProgress->setText(_("Import:"));
    ui->progressBar->setRange(0,m_ImportData.size());
    ui->progressBar->setValue(0);
    ui->progressBar->setRange(0,m_ImportData.size());
    int i = 0;
    std::string sdata,sql;
    std::string mPrj,mMeasur,mLayer;

    if(ui->checkBox->isChecked()){
        for( std::vector<std::string>::iterator it=m_ImportData.begin();it!=m_ImportData.end();it++){
            sdata = *it;
            std::vector<std::string> v = MSGINF::stringSplit(sdata,',');
            //工程 测量点 图层 gap gap- gap+ flush flush- flush+
            if(v.size()!=9){
                //qDebug() <<"Error Data:" << sdata.c_str() ;
                continue;
            }

            if(mPrj != v.at(0)){

                //CSql *dSql = new CSql();
                sql = string_sprintf("delete from fsapp where value='%s';",v.at(0).c_str());
                qDebug() << sql.c_str();
                m_Sql->exeSql(sql);
                sql = string_sprintf("delete from fslayer where fsapp='%s';",v.at(0).c_str());
                qDebug() << sql.c_str();
                m_Sql->exeSql(sql);
                sql = string_sprintf("delete from fspoint where fsapp='%s';",v.at(0).c_str());
                qDebug() << sql.c_str();
                m_Sql->exeSql(sql);

                //delete dSql;
            }
            mPrj = v.at(0);
        }


    }

    mPrj="";

    for( std::vector<std::string>::iterator it=m_ImportData.begin();it!=m_ImportData.end();it++){

        ui->progressBar->setValue(++i);

        sdata = *it;
        std::vector<std::string> v = MSGINF::stringSplit(sdata,',');
        //工程 测量点 图层 gap gap- gap+ flush flush- flush+
        if(v.size()!=9){
            qDebug() <<"Error Data:" << sdata.c_str() ;
            continue;
        }

        if(mPrj != v.at(0)){
            sql = string_sprintf("insert into fsapp(value) values('%s');",v.at(0).c_str());
            qDebug() << sql.c_str();
            m_Sql->exeSql(sql);
            sql = string_sprintf("insert into fslayer(value,fsapp) values('default','%s');",v.at(0).c_str());
            qDebug() << sql.c_str();

            m_Sql->exeSql(sql);
        }
        mPrj = v.at(0);

        if(mLayer != v.at(2)|| mPrj != v.at(0)){
            sql = string_sprintf("insert into fslayer(value,fsapp) values('%s','%s');",v.at(2).c_str(),v.at(0).c_str());
            qDebug() << sql.c_str();
            m_Sql->exeSql(sql);
        }
        mLayer = v.at(2);

        sql = string_sprintf("insert into fspoint(id,gap,gapmin,gapmax,flush,flushmin,flushmax,layer,fsapp) "
                                  "values('%s','%s','%s','%s','%s','%s','%s','%s','%s');"
                             ,v.at(1).c_str()
                             ,v.at(3).c_str(),v.at(4).c_str(),v.at(5).c_str()
                             ,v.at(6).c_str(),v.at(7).c_str(),v.at(8).c_str()
                             ,v.at(2).c_str(),v.at(0).c_str());
        qDebug() << sql.c_str();
        m_Sql->exeSql(sql);


    }
    m_Sql->exeSql("commit");
    ui->labelProgress->setText(_("Success:"));
}
